import { Subscription, Reducer, Effect } from 'umi';
import { querylistByShortName, queryProjectTree } from '@/services/gis';

export interface GisModelState {
  projectId: string | number;
}

export interface GisModelType {
  namespace: 'gis';
  state: GisModelState;
  effects: {
    getProjectTree: Effect;
    getlistByShortName: Effect;
  };
  reducers: {
    onSavePorjectId: Reducer<GisModelState>;
  };
  subscriptions: { setup: Subscription };
}

const GisModel: GisModelType = {
  namespace: 'gis',

  state: {
    projectId: 0,
  },

  effects: {
    /**
     * 获取项目结构树
     * projectId 和 code 在这里统一判断。
     * 涉及到 路由/postMessage 等方式修改这个值。
     * */
    *getProjectTree({ callback }, { call, select }) {
      const projectId = yield select(({ gis }: { gis: GisModelState }) => gis.projectId);
      const payload: {
        projectId?: string | number;
        code?: string;
      } = {};
      if (projectId === 0) {
        payload.projectId = projectId;
      } else {
        payload.code = projectId;
      }
      const response = yield call(queryProjectTree, payload);
      if (response.code === '1' && callback) {
        const { data } = response;
        callback(data);
      }
    },
    /** 获取模型分组属性 */
    *getlistByShortName({ payload, callback }, { call }) {
      const response = yield call(querylistByShortName, payload);
      if (callback) callback(response);
    },
  },
  reducers: {
    onSavePorjectId(state, { payload }) {
      return { ...state, projectId: payload };
    },
  },
  subscriptions: {
    setup({ history }): void {
      // // Subscribe history(url) change, trigger `load` action if pathname is `/`
      // history.listen(({ pathname, search }): void => {
      //   if (typeof window.ga !== 'undefined') {
      //     window.ga('send', 'pageview', pathname + search);
      //   }
      // });
    },
  },
};

export default GisModel;
